<?php
// +---------------------------------------------------------------------+
// | OneBase    | [ WE CAN DO IT JUST THINK ]                            |
// +---------------------------------------------------------------------+
// | Licensed   | http://www.apache.org/licenses/LICENSE-2.0 )           |
// +---------------------------------------------------------------------+
// | Author     | Bigotry <3162875@qq.com>                               |
// +---------------------------------------------------------------------+
// | Repository | https://gitee.com/Bigotry/OneBase                      |
// +---------------------------------------------------------------------+

namespace app\index\controller;

/**
 * 前端首页控制器
 */
class Login extends IndexBase
{
	// pc微信支付
	public function wxpay(){
		$s=$this->logicPayment->wxpay();
		var_dump($s);exit;
	}
	// pc支付宝支付

	public function zfpay()
	{
		$data=$this->param;
		$str=substr($data['order_sn'],0,2);
		if($str == 'ms') {
			$info = db('series_order')->where('order_sn', $data['order_sn'])->find();
			$res = [
				'subject'=>"购买".$info['name'],
				'body'=>"购买".$info['name']
			];
		}elseif($str == 'mc'){
			$info = db('money_order')->where('order_sn', $data['order_sn'])->find();
			$res = [
				'subject'=>"购买".$info['num']."枚MDC",
				'body'=>"购买".$info['num']."枚MDC"
			];
		}else{
			echo "<script>alert('订单错误！请重新下单！');window.location.href='/web/html/wallet.html';</script>";exit;
		}
		if(empty($info)){
			echo "<script>alert('订单错误！请重新下单！');window.location.href='/web/html/wallet.html';</script>";exit;
		}
		import('zfbpay.AopSdk');
		import("zfbpay.pagepay.service.AlipayTradeService");
		import("zfbpay.pagepay.buildermodel.AlipayTradePagePayContentBuilder");
		// 引入支付核心文件
		Vendor('Alipay.AopSdk');
		Vendor("Alipay.pagepay.service.AlipayTradeService");
		Vendor("Alipay.pagepay.buildermodel.AlipayTradePagePayContentBuilder");
		// 获取支付宝配置参数
		//$config = C("alipay");
		$config=Config('alipay_config');
		//$config=$this->servicePay->driverAlipay->config();
		//var_dump($config);exit;
		//商户订单号，商户网站订单系统中唯一订单号，必填
		$out_trade_no = $data['order_sn'];
		//订单名称，必填
		$subject = trim($res["subject"]);
		//付款金额，必填
		$total_amount = $info["money"];
		//商品描述，可空
		$body = trim($res["body"]);
		//构造参数
		$payRequestBuilder = new \AlipayTradePagePayContentBuilder();
		$payRequestBuilder->setBody($body);
		$payRequestBuilder->setSubject($subject);
		$payRequestBuilder->setTotalAmount($total_amount);
		$payRequestBuilder->setOutTradeNo($out_trade_no);
		$aop = new \AlipayTradeService($config);
		/**
		 * pagePay 电脑网站支付请求
		 * @param $builder 业务参数，使用buildmodel中的对象生成。
		 * @param $return_url 同步跳转地址，公网可以访问
		 * @param $notify_url 异步通知地址，公网可以访问
		 * @return $response 支付宝返回的信息
		 */
		$response = $aop->pagePay($payRequestBuilder,$config['return_url'],$config['notify_url']);
	}
	public function ailpay_notify(){
		// 引入核心类文件
		Vendor("Alipay.pagepay.service.AlipayTradeService");
		// 获取支付宝配置参数
		$config = C('alipay');
		// 获取返回值
		$arr = $_POST;
		// 检查数据
		$alipaySevice = new \AlipayTradeService($config);
		$alipaySevice->writeLog(var_export($_POST,true));
		$result = $alipaySevice->check($arr);
		// 判断检查结果数据
		if($result) {
			// 获取相关数据
			$out_trade_no = $arr['out_trade_no'];       //商户订单号
			$trade_no     = $arr['trade_no'];           //支付宝交易号
			$trade_status = $arr['trade_status'];       //交易状态
			$total_amount = $arr['total_amount'];       //交易金额
			$buyerid      = $arr['buyer_id'];           //卖家支付宝账号id

			// 判断数据是否做过处理，如果做过处理，return，没有做过处理，执行支付成功代码
			if($trade_status == 'TRADE_FINISHED' OR $trade_status == 'TRADE_SUCCESS') {

				//  修改订单状态
				//  修改用户拥有商品状态
				//  codeding……

				echo "success";
			}else{
				echo "fail";
			}

		}else {
			echo "fail";
		}
	}
    // 注册页面
    public function register()
    {	
		$data=$this->param;
		$data['is']=!empty($data['is'])?$data['is']:1;
		$this->assign('info',$data);
		return $this->fetch('register');
				         
    }
	// 注册
    public function registers()
    {	
		$data=$this->param;
		$arr=parse_config_array('shareMoney');
		$phone=$data['username'];
		$is=db('user')->where('username',$phone)->value('id');
		if(!empty($is)){
			echo json_encode(array('error'=>1,'msg'=>'该手机号已注册！'));exit;
		}
		if(!empty($data['tjid'])){
			$istj=db('user')->where('id',$data['tjid'])->value('id');
			if(empty($istj)){
				echo json_encode(array('error'=>1,'msg'=>'不存在该分享人！'));exit;
			}
		}else{
			$data['tjid']=10002;
		}
		db('user')->startTrans();
		$nocode=db('user')->where("id=".$data['tjid'])->value("nocodea");
		$salt=rand(1000,9999);
		$data['status'] = 1;
		$data['salt'] = $salt;
		$data['phone'] = $phone;
		$data['nocodea'] = $nocode.$data['tjid'].',';
		$data['create_time'] = time();		
		$data['password']  = data_md5_key($data['password'],$salt);	
		if( $msg = $this->checkCodes($phone,$data['code'])){
			echo json_encode(array('error'=>1,'msg'=>$msg));exit;	
		}
		$ida=db('user')->insertGetId($data);		
		$num=db('user')->where('id',$data['tjid'])->value('num');
		$isnum = config('mdc_share');
		if($num > intval($isnum)-2){
			$money_id=db('money')->where('user_id != 1 and status = 1 and `is` = 0 ')->order('id Asc')->value('id');
			money_log($data['tjid'],1);
			$count=db('user')->where('id',$data['tjid'])->value('count');
			$re=db('user')->where('id',$data['tjid'])->update(array('num'=>0,'count'=>$count+1));
		}else{
			$re=db('user')->where('id',$data['tjid'])->update(array('num'=>$num+1));
		}
		$rs=$this->getdaili($nocode.$data['tjid'],$ida);
		if($ida && $re){
			db('user')->commit();
			echo json_encode(array('error'=>0,'msg'=>'注册成功'));exit;
		}else{
			db('user')->rollback();
			echo json_encode(array('error'=>1,'msg'=>'注册失败'));exit;		
		}				         
    }
	/**
	 * 验证手机验证码
	 */
	private function checkCodes($phone,$code,$type=0)
	{
		$info=db('code')->field('code,create_time')->where("type=".$type." and phone='".$phone."'")->find();
		if($code != $info['code']){
			return '验证码错误';		
		}
		if(time()-$info['create_time'] > 180){
			return '验证码已过期';	
		}
		return false;
	}
	/**
     * 代理收入
     */
	 private function getdaili($str,$user_id){
		$arr=parse_config_array('agent_config');
		$id=db('user')->where("is_agent=1 and id IN (".$str.") ")->order(" field(id,".$str.") desc")->value('id');
		if(!empty($id)){
			$re = moneyyj_log($arr['money'],$id,8,$user_id);
			if($re){
				return true;
			}else{
				return false;
			}			
		}else{
			return true;
		}
	 }
	// 定时更新
	public function updateSeries()
	{
		$list=db('series_order')->where('stat = 1')->order('zf_time asc')->select();
		if(!empty($list)){
			foreach($list as $k=>$v){
				if($v['end_time'] <= time()){
					unset($info);
					db('series_order')->where('id',$v['id'])->update(array('stat'=>2));
					$info=db('company')->field('work,resume,end_time,user_id')->where('user_id',$v['user_id'])->find();
					if($info['end_time'] == $v['end_time']){
						db('company')->where('user_id',$v['user_id'])->update(array('end_time'=>'','resume'=>0,'work'=>0));
						if($v['workNum'] > $info['work']){
							$wnum=$v['workNum']-$info['work'];
							logAdd($info['user_id'],0,0,'套餐到期',(-1)*$wnum,4);
						}
						if($v['resumeNum'] > $info['resume']){
							$rnum=$v['resumeNum']-$info['resume'];
							logAdd($info['user_id'],0,1,'套餐到期',(-1)*$rnum,4);
						}
					}else{
						if($v['workNum'] > $info['work']){
							$wnum=$v['workNum']-$info['work'];
							logAdd($info['user_id'],0,0,'套餐到期',(-1)*$wnum,4);
							db('company')->where('user_id',$v['user_id'])->update(array('work'=>0));
						}else{
							db('company')->where('user_id',$v['user_id'])->setInc('resume',(-1)*$v['workNum']);
						}
						if($v['resumeNum'] > $info['resume']){
							$rnum=$v['resumeNum']-$info['resume'];
							logAdd($info['user_id'],0,1,'套餐到期',(-1)*$rnum,4);
							db('company')->where('user_id',$v['user_id'])->update(array('resume'=>0));
						}else{
							db('company')->where('user_id',$v['user_id'])->setInc('resume',(-1)*$v['resumeNum']);
						}
					}
				}
			}
		}
		return true;
	}
}
